package event_;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

/**
 * @author 王艺锡
 * @version 1.0
 */
public class BallMove extends JFrame {
    MyPanel mp = null;
    public static void main(String[] args) {
        BallMove ballMove = new BallMove();

    }
    public BallMove(){
        mp = new MyPanel();
        this.add(mp);
        this.setSize(400,300);
        //窗口JFrame对象可以监听键盘事件
        this.addKeyListener(mp);//mp实现了KeyListener，所以可以传入
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }
}

//面板，可以画出小球
//KeyListener是一个监听器，可以监听键盘时间
class MyPanel extends JPanel implements KeyListener {

    //为了让小球的坐标可以移动，所以把小球左上角的坐标设置为变量x,y
    int x = 10;
    int y = 10;
    @Override
    public void paint(Graphics g) {
        super.paint(g);
        g.fillOval(x,y,20,20);
    }

    //有字符输出时，该方法就会触发
    @Override
    public void keyTyped(KeyEvent e) {

    }
    //当某个键按下，该方法会触发
    @Override
    public void keyPressed(KeyEvent e) {
        //System.out.println((char) e.getKeyCode() + "键被按下");

        //根据按下的不同的键，控制小球上下左右移动
        if(e.getKeyCode() == KeyEvent.VK_DOWN){
        y++;
        }else if(e.getKeyCode() == KeyEvent.VK_UP){
            y--;
        }else if(e.getKeyCode() == KeyEvent.VK_RIGHT){
            x++;
        }else if(e.getKeyCode() == KeyEvent.VK_LEFT){
            x--;
        }


        this.repaint();

    }
    //当某个键释放，该方法会触发
    @Override
    public void keyReleased(KeyEvent e) {

    }
}
